package com.zang.util;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * 调用服务通用工具类
 *
 * @author by gs
 * @date 2022/4/26 3:29 PM
 */
@Slf4j
public class WebClientInvokeUtil {

    /**
     * DMS调用通用服务
     *
     * @param jsonParam 请求参数
     * @param url       请求地址
     * @return T
     */
    public <T> T toPost(String jsonParam, String url, Class<T> clazz) {
        JSONObject jsonObject = this.toPost(jsonParam, url);
        return BeanUtil.toBean(jsonObject, clazz);
    }

    public JSONObject toPost(String jsonParam, String url) {
        try {
            return JSONObject.parseObject(toPostString(jsonParam, url));
        } catch (Exception e) {
            log.error("接口调用失败,url:{} msg:{}", url, e.getMessage());
            return new JSONObject();
        }
    }

    public String toPostString(String jsonParam, String url) {
        if (Strings.isBlank(url)) {
            return null;
        }
        Mono<String> mono = WebClient.create().post().uri(url)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(jsonParam)).retrieve()
                .bodyToMono(String.class);
        return mono.block();
    }

}
